package 集合框架.Map.购物车;

import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 购物车类
 */
public class CartManager {

    //购物车
    private static Map<Integer,Cartltem> cartMap = new HashMap<>();

    //商品集合
    private static List<Goods> goodsList = new ArrayList<>();

    static {
        goodsList.add(new Goods(29129963,"Vue.js商城开发实战",51.40,183));
        goodsList.add(new Goods(27903761,"React前端开发实战",44.90,33));
        goodsList.add(new Goods(18941958,"2021新款黑色打底衫",57.20,183));
        goodsList.add(new Goods(15851366,"2021新款运动休闲鞋",216.67,99));
    }

    //获取所有的商品信息列表
    public static List<Goods> getGoodsList(){
        return goodsList;
    }

    //根据商品编号获取指定的商品对象
    public static Goods getGoodsById(int goodsId){
        for (int i = 0; i < goodsList.size(); i++) {
            Goods goods = goodsList.get(i);
            if(goods.getId() == goodsId){
                return goods;
            }
        }
        return null;
    }
    //根据索引获取指定的商品对象
    public static Goods getGoodsByIndex(int index){
        if(index < 0 || index >= goodsList.size() ) {
            throw new IndexOutOfBoundsException("数组索引超出范围 index = " + index);
        }
        Goods goods = goodsList.get(index);
        return goods;
    }

    static {
        cartMap.put(1000,new Cartltem(new Goods(1000,"Spring Boot编程思想",57.80,56),10,578.00));
    }

    //将商品添加到购物车中
    public static void addToCart(Goods goods){
        boolean goodsExists = cartMap.containsKey(goods.getId());
        Cartltem cartItem = null;
        if (! goodsExists) {
            cartItem = new Cartltem(goods, 1, goods.getPrice());
        }
        else {
            cartItem = cartMap.get(goods.getId());
            cartItem.setQuantity(cartItem.getQuantity() + 1);
            cartItem.setSubTotal(goods.getPrice() * cartItem.getQuantity());
        }
        cartMap.put(goods.getId(),cartItem);
    }


    //查看购物车中所购买的商品清单
    public static List<Cartltem> getCarItemList (){
        return new ArrayList<>(cartMap.values());
    }

    /**
     *     我的购物车功能列表：
     * 1、展示所有商品信息列表
     * 2、将商品添加到购物车中
     * 3、将商品从购物车中移除
     * 4、清空购物车
     * 5、计算购物中所有商品总计
     * 6、查看购物车中所购买的商品清单
     * 7、更新购物车中的商品数量
     * 8、结算，打印购物小票
     */

     //计算总价
    public static  double calcTotalPrice(){
        //1.遍历keySet()
      /*  double totalPrice = 0;
        for (Integer key : cartMap.keySet()) {
            CartItem item = cartMap.get(key);
            totalPrice += item.getSubTotal();
        }
        return totalPrice;*/
        //2.通过Map.entrySet使用iterator遍历 一个Entry表示一个键值对对象
    /* double totalPrice = 0;
        Iterator<Map.Entry<Integer, CartItem>> iter = cartMap.entrySet().iterator();
        for (;iter.hasNext();){
            Map.Entry<Integer, CartItem> current = iter.next();
            totalPrice += current.getValue().getSubTotal();
        }
        return totalPrice;*/
        //3.使用lambda表达式forEach遍历
        AtomicReference<Double> totalPrice = new AtomicReference<>(0.0);

        cartMap.forEach((k,v) -> {
            totalPrice.set(totalPrice.get() + v.getSubTotal());
        });
        return totalPrice.get();

    }

    //清空购物车
    public static  void clearCart(){
        if(cartMap.isEmpty()){
            System.out.println("购物车空空如也！");
        }
        else {
            cartMap.clear(); //清空Map集合
        }


    }
    //更改购买数量
    public static void changeQty(int gooDsLd,int qty){
        if(cartMap.containsKey(gooDsLd)) {
            Cartltem item = cartMap.get(gooDsLd);
            item.setQuantity(qty);
        }
        else {
            throw new RuntimeException("购物车不包含此商品编号");
        }

    }
    //去结算(下单）消费账单
    public static void doPay(){

        System.out.println("正在生成订单，请稍后 ...");
        try {
            Thread.sleep(1000L);
            System.out.println("订单生成成功！打印订单明细如下:");
            System.out.println("商品名\t\t数量\t\t小计");
            System.out.println("-----------------------------------------------------------");
            for (Cartltem item : cartMap.values()) {
                System.out.println(item.getGoods().getTitle() + "\t\t" + item.getQuantity() + "\t\t" + item.getSubTotal());
            }
            System.out.println("-----------------------------------------------------------");
            System.out.println("订单日期：" + new Date().toLocaleString());
            System.out.println("订单总金额:" + calcTotalPrice() + "元");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
